package org.jeecg.module.flow.meter.tcpserver.tcpServer;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @Author: 86176
 * @Date: 2024-05-24 12:42
 * @Version: 1.0
 */
public class HexServer {
    private static final String MESSAGE_TO_SEND = "680101009413050000007003001701010100A316";


    public static void main(String[] args) {
        int serverPort = 8503;

        try (ServerSocket serverSocket = new ServerSocket(serverPort)) {
            System.out.println("Server is listening on port " + serverPort + "...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Accepted connection from client.");

                // 发送消息给客户端
                sendFixedMessageToClient(clientSocket);
            }
        } catch (IOException e) {
            System.err.println("Error starting the server: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void sendFixedMessageToClient(Socket clientSocket) {
        try (OutputStream outputStream = clientSocket.getOutputStream()) {
            // 注意：这里假设消息不需要进行Hex解码，直接作为字符串发送
            byte[] bytes = (byte[]) new Hex().decode(MESSAGE_TO_SEND);
            System.out.println("bytes"+ Arrays.toString(bytes));
            System.out.println("MESSAGE_TO_SEND.getBytes(StandardCharsets.UTF_8)"+ Arrays.toString(MESSAGE_TO_SEND.getBytes(StandardCharsets.UTF_8)));
            outputStream.write(MESSAGE_TO_SEND.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            System.out.println("Message sent to client: " + MESSAGE_TO_SEND);
        } catch (IOException | DecoderException e) {
            System.err.println("Error sending message to client: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
